package com.wiloon.java8x.io.nio.netty;

/*
 * Created by Roy on 2015/9/1;
 */

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TcpClient {
    private static Logger logger = LoggerFactory.getLogger(TcpClient.class);
    public static String HOST = "127.0.0.1";
    public static int PORT = 9000;


    public static void main(String[] args) throws Exception {
        TcpClient tcpClient = new TcpClient();
        tcpClient.execute();
    }

    public void execute() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                //pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                //pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                pipeline.addLast("handler", new Handler());
            }
        });
        b.option(ChannelOption.SO_KEEPALIVE, true);

        Channel channel = b.connect(HOST, PORT).sync().channel();

        //channel.writeAndFlush("foo").sync();

    }

    static class Handler extends SimpleChannelInboundHandler<Object> {
        private static Logger logger = LoggerFactory.getLogger(Handler.class);

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            logger.info("channel read, msg from server:{}", msg);
        }


    }

}

